package gl.live.danceshow.ui.camera;

import gl.live.mediamux.sdk.AudioRecordCallback;
import gl.live.mediamux.sdk.SoxProcesser;
import gl.live.mediamux.sdk.event.PlayVideoEvent;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.media.MediaRecorder.AudioSource;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.app.mvmerged.R;

import de.greenrobot.event.EventBus;


@SuppressLint("NewApi") public class CameraPreviewActivity extends AbsCameraPreviewActivity implements
		View.OnClickListener, SeekBar.OnSeekBarChangeListener {

	private static final int REQ_REVIEW = 21;
	private int MAX_TIME_IN_MS = 10 * 60 * 1000;
	private ImageButton captureButton;
	private TextView titleText;
	private TimerTask task;
	private Timer timer;
	private ProgressBar progressBar;


	public static void actionRecord(@NonNull Activity activity, int reqRecord,
			String musicFile, String name) {
		activity.startActivityForResult(new Intent(activity,
				CameraPreviewActivity.class).putExtra("musicFile", musicFile)
				.putExtra("musicname", name), reqRecord);
	}
	
	public static void actionRecord(@NonNull Activity activity, int reqRecord,
			String musicFile, String name, String mergedvideo) {
		activity.startActivityForResult(new Intent(activity,
				CameraPreviewActivity.class).putExtra("musicFile", musicFile)
				.putExtra("musicname", name).putExtra("mergingvideofile", mergedvideo), reqRecord);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
	              != PackageManager.PERMISSION_GRANTED && Build.VERSION_CODES.M <= Build.VERSION.SDK_INT) {
	          //申请WRITE_EXTERNAL_STORAGE权限
	          requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.CAMERA},
	                  1);
	      }
		if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.CAMERA)
	              != PackageManager.PERMISSION_GRANTED && Build.VERSION_CODES.M <= Build.VERSION.SDK_INT) {
	          requestPermissions(new String[]{android.Manifest.permission.CAMERA},
	                  2);
	      }
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		// initPreFrame();
		captureButton = (ImageButton) findViewById(R.id.button_capture);
		captureButton.setOnClickListener(this);
		processIntent();

		ImageButton 
		setting = (ImageButton) findViewById(R.id.quit);
		setting.setOnClickListener(this);
		setting = (ImageButton) findViewById(R.id.buttonCancelSwitch);
		setting.setOnClickListener(this);
		
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		titleText = (TextView) findViewById(R.id.titleText);
		timer = new Timer("rec_count_down");

		onCaptureStopped();

        initSeekBar();
	}

	private int count = 0;


	private void playTimer() {
		setSwitchButtonState(true);
		toggleCapture(false);
	}


	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		processIntent();
	}

	private void processIntent() {
		Intent intent = getIntent();
		musicFile = "/sdcard/test.mp3";//intent.getStringExtra("musicFile");
		if (musicFile == null || intent == null) {
			Toast.makeText(this, "音乐文件未找到", Toast.LENGTH_LONG).show();
			finish();
		}
		MediaMetadataRetriever mmr = new MediaMetadataRetriever();

		try {
			mmr.setDataSource(musicFile);

			String duration = mmr
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
			MAX_TIME_IN_MS = Integer.parseInt(duration);
		} catch (Exception e) {
			Toast.makeText(this, "未知错误！", Toast.LENGTH_LONG).show();
		}
		
		mMergingVideoPath = intent.getStringExtra("mergingvideofile");
	}

	private void setViewVisible(int show) {
		mHandler.sendMessage(mHandler.obtainMessage(show,
				findViewById(R.id.preview_controller)));
		TextView text = (TextView) findViewById(R.id.tips_stop);
		text.setText(show == HIDE ? "停止" : "拍摄");
	}

	@Override
	protected void onCaptureStarted() {
		setViewVisible(HIDE);
		titleText.setText("正在摄像...");
		titleText.setCompoundDrawablesWithIntrinsicBounds(
				R.drawable.capture_rec_blink, 0, 0, 0);
		startCountDown();
//		mLyricManager.startUpdateLyric();
	}

	public static final long PROGRESS_STEP_IN_MS = 50L;

	private void startCountDown() {
		stopCountDown();
		task = new TimerTask() {
			private boolean bupdatefg = false;
			private int progress = 0;

			@Override
			public boolean cancel() {
				bupdatefg = false;
				progress = 0;
				return super.cancel();
			}

			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// debug("tick " + progress);
						progress += PROGRESS_STEP_IN_MS;
						if (progress >= MAX_TIME_IN_MS) {
							debug("progress >= MAX_TIME_IN_MS, toggle capture");
							stopCountDown();
							toggleCapture(true);
						} else {
//							if (!bupdatefg
//									&& mPreDrawable != null
//									&& (progress >= mPreDrawable
//											.getNumberOfFrames() * 3000)) {
//								// mPreDrawable.stop();
////								mFg.setBackground(mMainFgDrawable);
//								mMediaEngine
//										.setForegroundDrawable(mMainFgDrawable);
//								if (mMainFgDrawable instanceof AnimationDrawable) {
//									((AnimationDrawable) mMainFgDrawable)
//											.stop();
//									((AnimationDrawable) mMainFgDrawable)
//											.start();
//								}
//								bupdatefg = true;
//							}

							// if(!desdetailhiden && progress>=3000) {
							// desdetailhiden = true;
							// mDesDetails.setBackground(null);
							// }

							if (isRecording() && mMediaMux != null
									&& !mMediaMux.isPrepared())
								progress = 0;
//							progressBar.setProgress(progress);
//							mLyricManager.updatePostion(progress);

						}
					}
				});
			}
		};
		debug("start timer");
		timer.scheduleAtFixedRate(task, 0l, PROGRESS_STEP_IN_MS);
	}

	private void debug(String s) {
		Log.d("camera", s);
	}

	private void stopCountDown() {
		if (task != null) {
			task.cancel();
		}
		progressBar.setProgress(0);
	}

	@Override
	protected void onResume() {
		super.onResume();
		focusing = false;
		progressBar.setMax(MAX_TIME_IN_MS);
		EventBus.getDefault().register(this);
	}


	
	@Override
	protected void onPause() {
		mHandler.removeCallbacksAndMessages(null);
		stopCountDown();
		EventBus.getDefault().unregister(this);
		super.onPause();
	}

	@Override
	protected void onCaptureStopped() {
		stopCountDown();
		captureButton.setBackgroundResource(R.drawable.camera_recording_btn);
		titleText.setText("准备就绪");
		titleText.setCompoundDrawablesWithIntrinsicBounds(
				R.drawable.capture_rec_off, 0, 0, 0);
	}

	/**
	 * 视频已经处理完毕
	 * 
	 * @param mediaFilePath
	 */
	@Override
	protected void onCaptureFileReady(String mediaFilePath) {
		if (!TextUtils.isEmpty(mediaFilePath)) {
			final File file = new File(mediaFilePath);
			if (file.exists()) {
				try {
					MediaMetadataRetriever mRetriever = new MediaMetadataRetriever();
					mRetriever.setDataSource(mediaFilePath);
					Bitmap b = mRetriever.getFrameAtTime();
					if (b != null) {
						b = Bitmap.createScaledBitmap(b, 160, 90, true);
					}
				} catch (RuntimeException e) {
					Log.w(TAG, "setDataSource  fail " + e.getMessage());
				}

				scanVideoFile(mediaFilePath);
				setResult(RESULT_OK, new Intent().setData(Uri.fromFile(file)));
				finish();
			}
		}
	}

	private void scanVideoFile(final String filepath) {
		final MediaScannerConnection connect = new MediaScannerConnection(
				getApplicationContext(), null) {
			@Override
			public void onServiceConnected(ComponentName className,
					IBinder service) {
				super.onServiceConnected(className, service);
				scanFile(filepath, "video/avc");
			}
		};
		connect.connect();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQ_REVIEW:
			if (resultCode == RESULT_OK) {
				setResult(RESULT_OK, data);
				finish();
			} else {
				toast("请重试");
			}
			break;
		}
	}

	private void toast(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT)
				.show();
	}


	@Override
	public void onClick(@NonNull View v) {
		if (count != 0)
			return;
		switch (v.getId()) {
		case R.id.button_capture:
			if (!startok)
				return;
			if (isRecording()) {
				toggleCapture(true);
				return;
			}
			count = 0;
			playTimer();
			break;
		case R.id.quit:
			finish();
			break;

		case R.id.buttonCancelSwitch:
			setSwitchButtonState(false);
			if (!isRecording()) {
				openCamera(true);
				return;
			}
			stopCountDown();
			toggleCapture(false);
			setViewVisible(SHOW);
			break;
		default:
			break;
		}
	}

	private void setSwitchButtonState(boolean state) {
		TextView text = (TextView) findViewById(R.id.button_cancel);
		ImageButton setting = (ImageButton) findViewById(R.id.buttonCancelSwitch);
		if (state) {
			setting.setBackgroundResource(R.drawable.camera_cancel_btn);
			text.setText("取消");
		} else {
			setting.setBackgroundResource(R.drawable.camera_switch_selector);
			text.setText("切换");
		}
	}

	private static final int HIDE = 0;
	private static final int SHOW = 1;
	private static final int HIDE_FOCUS = 3;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			View v = (View) msg.obj;
			switch (msg.what) {
			case SHOW:
				v.setVisibility(View.VISIBLE);
				break;
			case HIDE:
				v.setVisibility(View.INVISIBLE);
				break;
			case HIDE_FOCUS:
				v.setVisibility(View.INVISIBLE);
			default:
				break;
			}
		};
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}


	public interface UpdateMusicPlayCallback {
		void updatePostion(long time);
	}

	@Override
	public void onProgressChanged(SeekBar VerticalSeekBar, int progress,
			boolean fromUser) {
		Log.d(TAG, "onProgressChanged " + progress);
		float y = ((float) (100 + VerticalSeekBar.getMax() - progress)) / 100.0f;
		Matrix m = new Matrix();
		Log.d(TAG,"mPreview.getCameraView().getPreviewHeight()  "+mPreview.getCameraView().getPreviewHeight() / 2);
		m.postScale(1, y, 0,mPreview.getCameraView().getPreviewHeight() / 2 );
		// if(defaultCameraId == 1) {
		// m.postScale(-1 ,1);
		// }
		mPreview.getCameraView().setPreviewTransform(m,y);
	}

	@Override
	public void onStartTrackingTouch(SeekBar VerticalSeekBar) {
		Log.d(TAG, "onStartTrackingTouch");
	}

	@Override
	public void onStopTrackingTouch(SeekBar VerticalSeekBar) {
		Log.d(TAG, "onStopTrackingTouch");
	}

	@Override
	protected void updateTorchView(boolean bshow) {
		
	}

	private boolean focusing = false;
	public void onEventMainThread(MotionEvent event) {
		if(focusing)
			return;
		if (count != 0)
			return;
		focusing = true;
		sendAutoFocus();
	}
	
	@Override
	public void onAutoFocus(boolean success, Camera camera) {
		Log.d(TAG,"onAutoFocus result = "+success);
		focusing = false;
		updateFocus(success?FocusState.SUCCESS:FocusState.FAIL);
	}

	@Override
	protected void updateFocus(final FocusState state) {
		
	}
	
    private void initSeekBar () {
    	SeekBar bar = (SeekBar)findViewById(R.id.cam_vol);
    	bar.setOnSeekBarChangeListener(monSeekBarListener);
    	bar = (SeekBar)findViewById(R.id.cam_flanger);
    	bar.setOnSeekBarChangeListener(monSeekBarListener);
    	bar = (SeekBar)findViewById(R.id.cam_pitch);
    	bar.setOnSeekBarChangeListener(monSeekBarListener);
    	bar = (SeekBar)findViewById(R.id.cam_highpass);
    	bar.setOnSeekBarChangeListener(monSeekBarListener);
    	bar = (SeekBar)findViewById(R.id.cam_reverb);
    	bar.setOnSeekBarChangeListener(monSeekBarListener);
    	
    }
    
    
SeekBar.OnSeekBarChangeListener monSeekBarListener =  new SeekBar.OnSeekBarChangeListener() {
		
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			
		}
		
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			
		}
		
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			Log.d(TAG,"onProgressChanged "+progress);
			switch (seekBar.getId()) {
			case R.id.cam_vol:
				mProcesser.setVol(progress);
				break;
			case R.id.cam_flanger:
				mProcesser.setflanger(progress);
				break;
			case R.id.cam_highpass:
				mProcesser.setHighPass(progress);
				break;
			case R.id.cam_pitch:
				mProcesser.setPitch(progress);
				break;
			case R.id.cam_reverb:
				mProcesser.setReverB(progress);
				break;
			default:
				break;
			}
		}
	};
	

}
